/**
 * Copyright (C)  Gadglet .
 *
 * This file is part of Gadglet
 *
 * Gadglet is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Gadglet is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Gadglet. If not, see <http://www.gnu.org/licenses/>.
 */

package com.gadglet.data;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.Extension;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.gadglet.core.GadgletRequestWrapper;
import com.gadglet.core.GadgletResponse;
import com.gadglet.core.GadgletResponse.ContentRecord;
import com.gadglet.core.RequestException;
import com.gadglet.params.ProfileFields;
import com.gadglet.params.SharingType;

/**
 * A simple DataStore content item with sharing functionality<br>
 * Developer needs to extends this class and add their application fields
 * <p>
 * Example:
 * Inheritance(customStrategy = "complete-table")
 * public class MyGadgetData extends PersonalShareableContentItem
* </p>
 * @see com.gadglet.data.utils.ContentItemHelper
 *
 */
@PersistenceCapable
public class PersonalShareableContentItem {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
	private String contentItemKey;

	@Persistent
	private Date creation;

	@Persistent
	private Date update;

	@Persistent
	private String ownerId;

	@Persistent(mappedBy = "personalShareableContentItem")
	@Element(dependent = "true")
	List<SharedItemReff> sharedItemReff = new ArrayList<SharedItemReff>();

	
	public List<SharedItemReff> getSharedItemReff() {
		return sharedItemReff;
	}

	public void removeItem(int index) {
		sharedItemReff.remove(index);
	}

	public void addSharedItemReff(SharedItemReff sharedItemReff) {
		this.sharedItemReff.add(sharedItemReff);
	}

	public String getOwnerId() {
		return ownerId;
	}

	protected PersonalShareableContentItem(GadgletRequestWrapper request) {

		this.creation = new java.util.Date();
		this.update = new java.util.Date();
		this.ownerId = request.getCurrentUserId();

	}

	
	public boolean isUserEdit(GadgletRequestWrapper request){
			
		if(this.sharedItemReff !=null)
			for(SharedItemReff ref: sharedItemReff)
				if((ref.getSharingType().equals(SharingType.EDIT)  || ref.getSharingType().equals(SharingType.OWNER) ) && ref.getSharedWithId().equals(request.getCurrentUserId()))
						return true;
		
		return false;
		
	}
	
	public boolean isUserRead(GadgletRequestWrapper request){
		
		if(this.sharedItemReff !=null)
			for(SharedItemReff ref: sharedItemReff)
				if( ref.getSharedWithId().equals(request.getCurrentUserId()))
						return true;
		
		return false;
		
	}
	
	
	public Date getUpdate() {
		return update;
	}

	public void setUpdate() {
		this.update = new java.util.Date();
	}

	public String getContentItemKey() {
		return contentItemKey;
	}

	public Date getCreation() {
		return creation;
	}

	
	/**
	 * @param request
	 * @return true if the current user is the owner of the item
	 */
	public boolean isOwnedByMe(GadgletRequestWrapper request) {

		if (request.getCurrentUserId().equals(getOwnerId()))
			return true;
		else
			return false;

	}
	
	/**
	 * Create JSON objects for user friends, sent to the client with the indication if the current item
	 * is shared with them
	 * @param request
	 * @param res
	 * @throws RequestException
	 */
	public void getFriendsSharing(GadgletRequestWrapper request, GadgletResponse res)
	throws RequestException {
		List <SharedItemReff> shares = getSharedItemReff();
		
		List <Friends> myFriends =  FriendsUtils.getMyFriends(request.getCurrentUserProfile());
		
		res.setHasMore(false);
		
		res.setAddPermit(false);
			
		if(myFriends==null)
			res.setTotalItemsNum(0);
		else{
			
			for(Friends friends: myFriends){
				
				ContentRecord record  = res.newItem();
				
				record.setContentName("myFriends");
					
				UserProfile profile = UserProfilesUtils.getProfileById(friends.getFriendId(request.getCurrentUserId()));
			
				record.addShareWith(profile.getProfileId());

				if(profile!=null && !profile.isPrivate())
					record.addItemField(ProfileFields.PROFILE_NICKNAME.getParamName(), profile.getNickName());
				else
					record.addItemField(ProfileFields.PROFILE_NICKNAME.getParamName(), ProfileFields.PROFILE_NICKNAME.getParamName());

					
						
				if( profile.getPhotoUrl()!=null &&  profile.getPhotoUrl().length()>0)
					record.addItemField(ProfileFields.PROFILE_THUMBNAILURL.getParamName(), profile.getPhotoUrl());
				
				for (SharedItemReff share : shares) {
					if (share.getSharedWithId().equals(profile.getProfileId())) 
							record.addShareType(share.getSharingType());

				
				}
				
				record.setGadgetPermissions(true, true, true);
			}
			
		}
	
	}
	
	/**
	 * Create JSON objects for the Domain user friends, sent to the client, with the indication if the current item
	 * is shared with them
	 * @param request
	 * @param res
	 * @throws RequestException
	 */
	public void getDomainFriendsSharing(GadgletRequestWrapper request, GadgletResponse res)
	throws RequestException {
		List <SharedItemReff> shares = getSharedItemReff();
		
		List <DomainUser> myFriends =  DomainUserFriendsUtils.getMyfriends(request);
		
		res.setHasMore(false);
		
		res.setAddPermit(false);
			
		if(myFriends==null)
			res.setTotalItemsNum(0);
		else{
			
			for(DomainUser friend: myFriends){
				
				ContentRecord record  = res.newItem();
				
				record.setContentName("myFriends");
					
			
				record.addShareWith(friend.getUniqueId());

				
				record.addItemField(ProfileFields.PROFILE_NICKNAME.getParamName(), friend.getNickName());
				
				record.addItemField(ProfileFields.PROFILE_TITLE.getParamName(), friend.getTitle());

				
				if( friend.getPhotoUrl()!=null &&  friend.getPhotoUrl().length()>0)
					record.addItemField(ProfileFields.PROFILE_THUMBNAILURL.getParamName(), friend.getPhotoUrl());
				
				for (SharedItemReff share : shares) {
					if (share.getSharedWithId().equals(friend.getUniqueId()))
						record.addShareType(share.getSharingType());

				
				}
				
				record.setGadgetPermissions(true, true, true);
			}
			
		}
	
	}
	

	

}
